function thousandSeparator(num) {
    const str = num.toString();
    const result = str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
    return result;
}

// Example Usage:
console.log(thousandSeparator(1234567));         // Output: "1,234,567"
console.log(thousandSeparator(987654321.02));    // Output: "987,654,321.02"  